package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.customer.service.CustomerAuthorizationService;
import com.sz.biz.common.customer.service.CustomerRoleService;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.service.role.MembershipType;
import com.sz.common.core.service.role.RoleMembership;
import com.sz.common.core.system.dto.MenuPermissionDto;
import com.sz.common.core.system.entity.Role;
import com.sz.common.core.system.service.AuthorizationService;
import com.sz.common.core.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service("CustomerAuthorizationService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerAuthorizationServiceImpl implements CustomerAuthorizationService {

    @Autowired
    private AuthorizationService authorizationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private CustomerRoleService cusRoleService;

    @Override
    public void saveCusUserIdAndMenuAndPermission(List<MenuPermissionDto> list, Integer cusUserId) {
        RoleMembership roleMemberShip = new RoleMembership(cusUserId, MembershipType.CUSTOMER);
        List<Role> roles = roleService.getRoleByMember(roleMemberShip);
        //一个用户对应一个角色，所以这里的list.size=1
        if ((roles == null || roles.size() == 0)) {
            //说明有相应的权限，需要生成一个角色
            if (list != null && list.size() != 0) {
                Role role = roleService.getRoleCode(PrincipalUtils.getDomainId());
                role.setName(cusUserId + "");
                role.setDomainId(PrincipalUtils.getDomainId());
                int roleId = roleService.saveRole(role);
                cusRoleService.assignRoleMembers(roleId, Arrays.asList(roleMemberShip));
                authorizationService.saveMenuAndPermissionAuth(list, roleId);
            }
            //否则说明 没有任何权限需要角色
        } else {
            if (list == null || list.size() == 0) {
                roleService.deleteRoleById(roles.get(0).getId());
            } else {
                authorizationService.saveMenuAndPermissionAuth(list, roles.get(0).getId());
            }
        }
    }
}
